# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

library(plyr)
library(gridExtra)
library(scales)
library(egg)
library(VennDiagram)
library(optparse)
library(magrittr)
library(tidyverse)

createWhenNoExist <- function(f){
    ! dir.exists(f) && dir.create(f)
}

option_list <- list(
make_option("--i", default = "AllMet.csv", type = "character", help = "metabolite data file"),
make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file"),
make_option("--config", default = "config.csv", type = "character", help = "config file")
)
opt <- parse_args(OptionParser(option_list = option_list))

configData <- read_csv(opt$config,col_names = F) %>%
set_colnames(c("arg", "value"))

configData

pValue <- configData %>%
    filter(arg == "diffMethod.pValue") %>%
    .$value %>%
    as.numeric()

vipNum <- configData %>%
    filter(arg == "oplsda.vip") %>%
    .$value %>%
    as.numeric()

log2FcNum <- configData %>%
    filter(arg == "diffMethod.log2FC") %>%
    .$value %>%
    as.numeric()

fdr <- configData %>%
    filter(arg == "diffMethod.fdr") %>%
    .$value %>%
    as.numeric()

isInter <- configData %>%
    filter(arg == "isInter") %>%
    .$value %>%
    as.character()

oplsdaValid = read_tsv("../oplsda/valid.txt") %>%
    .$valid %>%
    as.logical()

if (! oplsdaValid) {
    configData <- configData %>%
        filter(arg != "isInter") %>%
        add_row(arg = "isInter", value = "oplsda")
}


sampleInfo <- read.csv(opt$g, header = T, stringsAsFactors = F) %>%
select(c("SampleID", "ClassNote"))

sampleIds <- read.csv(opt$g, header = T, stringsAsFactors = F) %>%
    select(c("SampleID", "ClassNote")) %>%
    .$SampleID

inputData <- read.csv(opt$i, header = T, stringsAsFactors = F) %>%
select(c("Class", "HMDB", "KEGG", "Metabolite", sampleIds))

data <- inputData %>%
select(- c("HMDB", "KEGG", "Class"))


classData <- inputData %>%
select(c("Class", "HMDB", "KEGG", "Metabolite"))

parent <- "./"
createWhenNoExist(parent)
uniFileName <- paste0("../uni/", parent, "/AllMet_Test.csv")
uniData <- read.csv(uniFileName, header = T, stringsAsFactors = F, comment.char = "") %>%
    rowwise() %>%
    do({
        result <- as.data.frame(.)
        p <- result[1, "P"]
        q <- result[1, "FDR"]
        value <- if (p < pValue) {
            1
        }else 0
        result$IS_Uni_P_Sig <- value
        result$IS_Uni_FDR_Sig <- ifelse(q <= fdr, 1, 0)
        logFC <- result[1, "log2FC"]
        result$IS_log2FC_Sig <- as.numeric(abs(logFC) >= log2FcNum)
        result$IS_Uni_Test_Pooled_Sig <- as.numeric(result$IS_log2FC_Sig &
            result$IS_Uni_FDR_Sig &
            result$IS_Uni_P_Sig)
        result
    }) %>%
    mutate(Uni_P = P, Uni_FDR = FDR) %>%
    select(c("Metabolite", "Uni_P", "IS_Uni_P_Sig", "Uni_FDR", "IS_Uni_FDR_Sig", "FC","log2FC", "IS_log2FC_Sig", "IS_Uni_Test_Pooled_Sig"))
print(head(uniData))
mulFileName <- paste0("../oplsda/", parent, "/OPLSDA_VIP.csv")
mulData <- read.csv(mulFileName, header = T, stringsAsFactors = F, comment.char = "") %>%
    rename(vip = VIP, cor = Corr.Coeffs.) %>%
    rowwise() %>%
    do({
        result <- as.data.frame(.)
        vip <- result[1, "vip"]
        value <- if (vip >= vipNum & oplsdaValid) {
            1
        }else 0
        result$IS_OPLSDA_Sig <- value
        result
    }) %>%
    rename(OPLSDA_VIP = vip) %>%
    select(c("Metabolite", "OPLSDA_VIP", "IS_OPLSDA_Sig"))
head(mulData)
print(isInter)
finalDf <- classData %>%
    left_join(uniData, by = c("Metabolite")) %>%
    left_join(mulData, by = c("Metabolite")) %>%
    rowwise() %>%
    do({
        result <- as.data.frame(.)
        result$Inter_Sig <- (result$IS_Uni_Test_Pooled_Sig & result$IS_OPLSDA_Sig) %>%
        as.numeric()
        result$Union_Sig <- (result$IS_Uni_Test_Pooled_Sig | result$IS_OPLSDA_Sig) %>%
        as.numeric()
        result$IS_All_Test_Pooled_Sig <- result$Inter_Sig
        result
    }) %>%
    left_join(data, by = c("Metabolite"))

isInter

if (isInter == "F") {
    finalDf <- finalDf %>%
    mutate(IS_All_Test_Pooled_Sig = Union_Sig)
}
if (isInter == "auto") {
    diffData <- finalDf %>%
    filter(IS_All_Test_Pooled_Sig == 1)
    if (nrow(diffData) == 0) {
        finalDf <- finalDf %>%
        mutate(IS_All_Test_Pooled_Sig = Union_Sig)
        if (oplsdaValid) {
            configData <- configData %>%
                filter(arg != "isInter") %>%
                add_row(arg = "isInter", value = "uni")
        }
    }
}

finalDf <- finalDf %>%
select(- c("Inter_Sig", "Union_Sig"))

head(finalDf)

outFileName <- paste0(parent, "/AllMet_Tests_Joined.csv")
write.csv(finalDf, outFileName, row.names = F)

write_csv(configData, opt$config, col_names = F)





